package com.ytktt.study.week3.task346.gateway.util;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;

@Slf4j
public class RequestUtil {

    public static String getIpAddress(FullHttpRequest request, ChannelHandlerContext ctx) {
        String ip = null;
        try {
            ip = request.headers().get(IpAddressEnum.X_FORWARDED_FOR.getName());
            if (StringUtils.isEmpty(ip) || IpAddressEnum.UNKNOWN.getName().equalsIgnoreCase(ip)) {
                ip = request.headers().get(IpAddressEnum.PROXY_CLIENT_IP.getName());
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || IpAddressEnum.UNKNOWN.getName().equalsIgnoreCase(ip)) {
                ip = request.headers().get(IpAddressEnum.WL_PROXY_CLIENT_IP.getName());
            }
            if (StringUtils.isEmpty(ip) || IpAddressEnum.UNKNOWN.getName().equalsIgnoreCase(ip)) {
                ip = request.headers().get(IpAddressEnum.HTTP_CLIENT_IP.getName());
            }
            if (StringUtils.isEmpty(ip) || IpAddressEnum.UNKNOWN.getName().equalsIgnoreCase(ip)) {
                ip = request.headers().get(IpAddressEnum.HTTP_X_FORWARDED_FOR.getName());
            }
            if (StringUtils.isEmpty(ip) || IpAddressEnum.UNKNOWN.getName().equalsIgnoreCase(ip)) {
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                ip = address.getAddress().getHostAddress();
            }
        } catch (Exception e) {
            log.error("IpUtil ERROR ", e);
        }

        return ip;
    }
}
